<template>
  <div class="form-designer">
    <!-- 左侧组件面板 -->
    <ComponentPanel
      :form-items="formItems"
      :selected-index="selectedIndex"
      @select-item="selectItem"
      @copy-item="copyItem"
      @delete-item="deleteItem"
      @delete-grid-child="deleteGridChild"
    />

    <!-- 中间设计区域 -->
    <DesignCanvas
      :form-items="formItems"
      :form-model="formModel"
      :form-config="formConfig"
      :selected-index="selectedIndex"
      :selected-grid-column="selectedGridColumn"
      :can-undo="canUndo"
      :can-redo="canRedo"
      @select-item="selectItem"
      @select-grid-column="selectGridColumn"
      @copy-item="copyItem"
      @delete-item="deleteItem"
      @undo-action="undoAction"
      @redo-action="redoAction"
      @preview-form="previewForm"
      @generate-code="generateCode"
      @clear-form="clearForm"
      @save-form="saveForm"
      @add-form-item="addFormItem"
      @move-form-item="moveFormItem"
      @import-form="importForm"
      @export-form="exportForm"
    />

    <!-- 右侧属性面板 -->
    <PropertyPanel
      :selected-item="selectedItem"
      :form-config="formConfig"
      :selected-grid-column="selectedGridColumn"
      @add-option="addOption"
      @remove-option="removeOption"
      @update-grid-columns="updateGridColumns"
      @clear-field-value="clearFieldValue"
    />

    <!-- 预览对话框 -->
    <PreviewDialog
      v-model="previewVisible"
      :form-items="formItems"
      :form-config="formConfig"
      :form-model="formModel"
      @close="previewVisible = false"
    />

    <!-- 代码生成对话框 -->
    <CodeDialog
      v-model="codeVisible"
      :form-items="formItems"
      :form-config="formConfig"
      @close="codeVisible = false"
    />
  </div>
</template>

<script setup>
import ComponentPanel from "./components/ComponentPanel.vue";
import CodeDialog from "./components/CodeDialog.vue";
import DesignCanvas from "./components/DesignCanvas.vue";
import PreviewDialog from "./components/PreviewDialog.vue";
import PropertyPanel from "./components/PropertyPanel.vue";

import { ref, reactive, computed, watch, getCurrentInstance } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import tool from "@/utils/tool";
import { useI18n } from "vue-i18n";

// 国际化
const { t } = useI18n();
const { proxy } = getCurrentInstance();
const router = useRouter();

const props = defineProps({
  schema: {
    type: Object,
    default: null,
  },
  schemaId: {
    type: String,
    default: "",
  },
});

// 表单配置
const formConfig = reactive({
  labelWidth: "100px",
  labelPosition: "right",
  size: "default",
  showSubmitButton: true,
  showResetButton: false,
  // 表单事件配置
  events: {
    submit: "",
    reset: "",
    validate: "",
    validateField: "",
    clearValidate: "",
  },
});

// 表单项列表
const formItems = ref([]);
const formModel = ref({});
const selectedIndex = ref(-1);
const selectedGridColumn = ref("");

// 预览相关
const previewVisible = ref(false);
const previewModel = ref({});

// 代码生成相关
const codeVisible = ref(false);

// 撤销重做相关
const historyStack = ref([]);
const historyIndex = ref(-1);
const maxHistorySize = 50;

// 撤销重做状态
const canUndo = computed(() => historyIndex.value > 0);
const canRedo = computed(
  () => historyIndex.value < historyStack.value.length - 1
);

// 当前选中的表单项
const selectedItem = computed(() => {
  if (selectedIndex.value === -1) return null;

  // 如果是字符串格式，说明选中的是栅格子组件
  if (typeof selectedIndex.value === "string") {
    const parts = selectedIndex.value.split("-");
    if (parts.length === 3) {
      const [gridIndex, colIndex, childIndex] = parts.map(Number);
      const gridItem = formItems.value[gridIndex];
      if (
        gridItem &&
        gridItem.type === "grid" &&
        gridItem.columns[colIndex] &&
        gridItem.columns[colIndex].children
      ) {
        return gridItem.columns[colIndex].children[childIndex];
      }
    }
    return null;
  }

  // 普通组件选择
  return selectedIndex.value >= 0 ? formItems.value[selectedIndex.value] : null;
});

// 移动表单项
const moveFormItem = (fromIndex, toIndex) => {
  if (
    fromIndex === toIndex ||
    fromIndex < 0 ||
    fromIndex >= formItems.value.length ||
    toIndex < 0 ||
    toIndex > formItems.value.length
  ) {
    return;
  }

  // 调整插入位置
  let actualToIndex = toIndex;
  if (fromIndex < toIndex) {
    actualToIndex = toIndex - 1;
  }

  const item = formItems.value.splice(fromIndex, 1)[0];
  formItems.value.splice(actualToIndex, 0, item);

  // 更新选中索引
  selectedIndex.value = actualToIndex;

  saveHistory();
};

// 保存历史状态
const saveHistory = () => {
  const currentState = {
    formItems: JSON.parse(JSON.stringify(formItems.value)),
    formModel: JSON.parse(JSON.stringify(formModel.value)),
    formConfig: JSON.parse(JSON.stringify(formConfig)),
  };

  // 如果当前不在历史栈顶部，删除后面的历史
  if (historyIndex.value < historyStack.value.length - 1) {
    historyStack.value = historyStack.value.slice(0, historyIndex.value + 1);
  }

  historyStack.value.push(currentState);

  // 限制历史栈大小
  if (historyStack.value.length > maxHistorySize) {
    historyStack.value.shift();
  } else {
    historyIndex.value++;
  }
};

// 添加表单项
const addFormItem = (componentData, insertIndex = -1) => {
  const key = `field_${Date.now()}`;
  const newItem = {
    key,
    type: componentData.type,
    field: key,
    label: componentData.label,
    placeholder: `请输入${componentData.label}`,
    required: false,
    disabled: false,
    clearable: true,
    ...getDefaultProps(componentData.type),
  };

  // 栅格布局组件特殊处理
  if (componentData.type === "grid") {
    newItem.columns = [
      {
        span: 12,
        children: [],
      },
      {
        span: 12,
        children: [],
      },
    ];
    delete newItem.placeholder;
    delete newItem.clearable;
  }

  if (insertIndex >= 0 && insertIndex <= formItems.value.length) {
    formItems.value.splice(insertIndex, 0, newItem);
    selectedIndex.value = insertIndex;
  } else {
    formItems.value.push(newItem);
    selectedIndex.value = formItems.value.length - 1;
  }

  // 栅格布局组件不需要在formModel中添加数据
  if (componentData.type !== "grid") {
    formModel.value[key] = getDefaultValue(componentData.type, newItem);
  }

  // 保存历史状态
  saveHistory();
};

// 获取默认属性
const getDefaultProps = (type) => {
  const props = {};

  switch (type) {
    case "number":
      props.min = 0;
      props.max = 100;
      props.step = 1;
      props.precision = undefined;
      props.stepStrictly = false;
      props.controlsPosition = "";
      break;
    case "select":
      props.multiple = false;
      props.collapseTags = false;
      props.multipleLimit = 0;
      props.options = [
        {
          label: `${t("formDesigner.propertyPanel.common.option1")}`,
          value: "1",
        },
        {
          label: `${t("formDesigner.propertyPanel.common.option2")}`,
          value: "2",
        },
      ];
      break;
    case "cascader":
      props.multiple = false;
      props.collapseTags = false;
      props.clearable = true;
      props.filterable = false;
      props.separator = " / ";
      props.showAllLevels = true;
      props.expandTrigger = "click";
      props.checkStrictly = false;
      props.options = [
        {
          value: "1",
          label: `${t("formDesigner.propertyPanel.common.exampleLevel1")} 1`,
          children: [
            {
              value: "1-1",
              label: `${t(
                "formDesigner.propertyPanel.common.exampleLevel2"
              )} 1-1`,
              children: [
                {
                  value: "1-1-1",
                  label: `${t(
                    "formDesigner.propertyPanel.common.exampleLevel3"
                  )} 1-1-1`,
                },
              ],
            },
          ],
        },
        {
          value: "2",
          label: `${t("formDesigner.propertyPanel.common.exampleLevel1")} 2`,
          children: [
            {
              value: "2-1",
              label: `${t(
                "formDesigner.propertyPanel.common.exampleLevel2"
              )} 2-1`,
            },
            {
              value: "2-2",
              label: `${t(
                "formDesigner.propertyPanel.common.exampleLevel2"
              )} 2-2`,
            },
          ],
        },
      ];
      break;
    case "radio":
      props.border = false;
      props.options = [
        {
          label: `${t("formDesigner.propertyPanel.common.option1")}`,
          value: "1",
        },
        {
          label: `${t("formDesigner.propertyPanel.common.option2")}`,
          value: "2",
        },
      ];
      props.buttonStyle = false;
      break;
    case "checkbox":
      props.options = [
        {
          label: `${t("formDesigner.propertyPanel.common.option1")}`,
          value: "1",
        },
        {
          label: `${t("formDesigner.propertyPanel.common.option2")}`,
          value: "2",
        },
      ];
      props.border = false;
      props.buttonStyle = false;
      props.min = undefined;
      props.max = undefined;
      break;
    case "date":
      props.dateType = "date";
      props.multiple = false;
      props.rangeable = false;
      break;
    case "time":
      props.isRange = false;
      props.format = "HH:mm:ss";
      break;
    case "textarea":
      props.rows = 3;
      props.autosize = false;
      props.maxlength = undefined;
      props.showWordLimit = false;
      break;
    case "switch":
      props.activeText = undefined;
      props.inactiveText = undefined;
      props.activeValue = undefined;
      props.inactiveValue = undefined;
      break;
    case "grid":
      // 栅格布局组件的默认属性
      props.gutter = 0;
      break;
    case "tree":
      props.showCheckbox = true;
      props.checkStrictly = false;
      props.defaultExpandAll = false;
      props.expandOnClickNode = true;
      props.checkOnClickNode = false;
      props.accordion = false;
      props.indent = 18;
      props.nodeKey = "id";
      props.draggable = false;
      props.lazy = false;
      props.data = [
        {
          id: 1,
          label: `${t("formDesigner.propertyPanel.common.exampleLevel1")} 1`,
          children: [
            {
              id: 4,
              label: `${t(
                "formDesigner.propertyPanel.common.exampleLevel2"
              )} 1-1`,
              children: [
                {
                  id: 9,
                  label: `${t(
                    "formDesigner.propertyPanel.common.exampleLevel3"
                  )} 1-1-1`,
                },
                {
                  id: 10,
                  label: `${t(
                    "formDesigner.propertyPanel.common.exampleLevel3"
                  )} 1-1-2`,
                },
              ],
            },
          ],
        },
        {
          id: 2,
          label: `${t("formDesigner.propertyPanel.common.exampleLevel1")} 2`,
          children: [
            {
              id: 5,
              label: `${t(
                "formDesigner.propertyPanel.common.exampleLevel2"
              )} 2-1`,
            },
            {
              id: 6,
              label: `${t(
                "formDesigner.propertyPanel.common.exampleLevel2"
              )} 2-2`,
            },
          ],
        },
        {
          id: 3,
          label: `${t("formDesigner.propertyPanel.common.exampleLevel1")} 3`,
          children: [
            {
              id: 7,
              label: `${t(
                "formDesigner.propertyPanel.common.exampleLevel2"
              )} 3-1`,
            },
            {
              id: 8,
              label: `${t(
                "formDesigner.propertyPanel.common.exampleLevel2"
              )} 3-2`,
            },
          ],
        },
      ];
      break;
    case "treeselect":
      props.multiple = false;
      props.checkStrictly = false;
      props.expandOnClickNode = true;
      props.checkOnClickNode = false;
      props.filterable = false;
      props.accordion = false;
      props.showCheckbox = false;
      props.nodeKey = "value";
      props.indent = 18;
      props.data = [
        {
          value: "1",
          label: `${t("formDesigner.propertyPanel.common.exampleLevel1")} 1`,
          children: [
            {
              value: "1-1",
              label: `${t(
                "formDesigner.propertyPanel.common.exampleLevel2"
              )} 1-1`,
              children: [
                {
                  value: "1-1-1",
                  label: `${t(
                    "formDesigner.propertyPanel.common.exampleLevel3"
                  )} 1-1-1`,
                },
              ],
            },
          ],
        },
        {
          value: "2",
          label: `${t("formDesigner.propertyPanel.common.exampleLevel1")} 2`,
          children: [
            {
              value: "2-1",
              label: `${t(
                "formDesigner.propertyPanel.common.exampleLevel2"
              )} 2-1`,
            },
            {
              value: "2-2",
              label: `${t(
                "formDesigner.propertyPanel.common.exampleLevel2"
              )} 2-2`,
            },
          ],
        },
      ];
      break;
    case "slider":
      props.min = 0;
      props.max = 100;
      props.step = 1;
      props.showInput = false;
      props.showInputControls = true;
      props.showStops = false;
      props.showTooltip = true;
      props.formatTooltip = undefined;
      props.range = false;
      props.vertical = false;
      props.height = "200px";
      props.marks = undefined;
      break;
    case "descriptions":
      props.title = "";
      props.column = 3;
      props.size = "default";
      props.border = false;
      props.direction = "horizontal";
      props.extra = "";
      props.items = [
        {
          label: t("formDesigner.propertyPanel.descriptions.exampleUsername"),
          value: t(
            "formDesigner.propertyPanel.descriptions.exampleUsernameValue"
          ),
          span: 1,
        },
        {
          label: t("formDesigner.propertyPanel.descriptions.examplePhone"),
          value: t("formDesigner.propertyPanel.descriptions.examplePhoneValue"),
          span: 1,
        },
        {
          label: t("formDesigner.propertyPanel.descriptions.exampleAddress"),
          value: t(
            "formDesigner.propertyPanel.descriptions.exampleAddressValue"
          ),
          span: 2,
          align: "left",
        },
        {
          label: t("formDesigner.propertyPanel.descriptions.exampleRemark"),
          value: t(
            "formDesigner.propertyPanel.descriptions.exampleRemarkValue"
          ),
          span: 3,
        },
      ];
      break;
  }

  return props;
};

// 获取默认值
const getDefaultValue = (type, item = null) => {
  switch (type) {
    case "number":
      return 0;
    case "checkbox":
      return [];
    case "switch":
      return false;
    case "tree":
      return [];
    case "tree-select":
      return "";
    case "slider":
      // 如果是范围选择模式，返回数组，否则返回数字
      if (item && item.range) {
        return [0, 50];
      }
      return 0;
    case "descriptions":
      return {};
    default:
      return "";
  }
};

// 选择表单项
const selectItem = (index) => {
  selectedIndex.value = index;
  selectedGridColumn.value = ""; // 清空栅格列选择
};

// 选择栅格列
const selectGridColumn = (gridIndex, colIndex) => {
  selectedGridColumn.value = `${gridIndex}-${colIndex}`;
  selectedIndex.value = gridIndex; // 同时选中栅格组件
};

// 复制表单项
const copyItem = (index) => {
  const item = { ...formItems.value[index] };
  const key = `field_${Date.now()}`;
  item.key = key;
  item.field = key;
  item.label = `${item.label}_copy`;

  formItems.value.splice(index + 1, 0, item);
  formModel.value[key] = getDefaultValue(item.type, item);

  // 保存历史状态
  saveHistory();
};

// 删除表单项
const deleteItem = (index) => {
  const item = formItems.value[index];
  delete formModel.value[item.field];
  formItems.value.splice(index, 1);
  selectedIndex.value = -1;

  // 保存历史状态
  saveHistory();
};

// 删除栅格子组件
const deleteGridChild = (gridIndex, colIndex, childIndex) => {
  const gridItem = formItems.value[gridIndex];
  if (
    gridItem &&
    gridItem.type === "grid" &&
    gridItem.columns &&
    gridItem.columns[colIndex]
  ) {
    const child = gridItem.columns[colIndex].children[childIndex];
    if (child) {
      // 删除表单数据
      delete formModel.value[child.field];
      // 删除子组件
      gridItem.columns[colIndex].children.splice(childIndex, 1);
      // 清空选择
      selectedIndex.value = -1;
      selectedGridColumn.value = "";

      // 保存历史状态
      saveHistory();
    }
  }
};

// 添加选项
const addOption = () => {
  if (selectedItem.value && selectedItem.value.options) {
    selectedItem.value.options.push({
      label: `${t("formDesigner.propertyPanel.common.option")}${
        selectedItem.value.options.length + 1
      }`,
      value: `${selectedItem.value.options.length + 1}`,
    });
  }
};

// 删除选项
const removeOption = (index) => {
  if (selectedItem.value && selectedItem.value.options) {
    selectedItem.value.options.splice(index, 1);
  }
};

// 清空字段值
const clearFieldValue = (fieldName) => {
  if (formModel.value.hasOwnProperty(fieldName)) {
    // 根据字段对应的组件类型设置默认值
    const item =
      formItems.value.find((item) => item.field === fieldName) ||
      formItems.value.find(
        (item) =>
          item.type === "grid" &&
          item.columns?.some((col) =>
            col.children?.some((child) => child.field === fieldName)
          )
      );

    if (item) {
      let targetItem = item;
      // 如果是栅格布局中的子组件，找到实际的子组件
      if (item.type === "grid") {
        for (const col of item.columns) {
          const child = col.children?.find(
            (child) => child.field === fieldName
          );
          if (child) {
            targetItem = child;
            break;
          }
        }
      }

      formModel.value[fieldName] = getDefaultValue(targetItem.type, targetItem);
    } else {
      // 如果找不到对应的组件，设置为空字符串
      formModel.value[fieldName] = "";
    }
  }
};

// 栅格布局相关方法
const updateGridColumns = (action, index) => {
  if (!selectedItem.value || selectedItem.value.type !== "grid") {
    return;
  }

  const gridItem = selectedItem.value;

  switch (action) {
    case "add":
      // 添加新列
      const newColumn = {
        span: 12,
        children: [],
      };
      gridItem.columns.push(newColumn);
      // 重新分配列宽
      redistributeGridColumnSpans(gridItem.columns);
      break;

    case "remove":
      // 删除列
      if (
        gridItem.columns.length > 1 &&
        index >= 0 &&
        index < gridItem.columns.length
      ) {
        // 删除列中的子组件数据
        const column = gridItem.columns[index];
        if (column.children) {
          column.children.forEach((child) => {
            delete formModel.value[child.field];
          });
        }

        // 检查当前选中的栅格列是否是要删除的列
        if (selectedGridColumn.value) {
          const parts = selectedGridColumn.value.split("-");
          if (parts.length > 1) {
            const selectedGridIndex = parseInt(parts[0]);
            const selectedColIndex = parseInt(parts[1]);

            // 如果选中的是当前栅格的列
            if (selectedGridIndex === selectedIndex.value) {
              // 如果选中的是要删除的列
              if (selectedColIndex === index) {
                selectedGridColumn.value = ""; // 清空选中状态
              } else if (selectedColIndex > index) {
                // 如果选中的列在删除列之后，需要更新索引
                selectedGridColumn.value = `${selectedGridIndex}-${
                  selectedColIndex - 1
                }`;
              }
            }
          }
        }

        gridItem.columns.splice(index, 1);
        // 重新分配列宽
        redistributeGridColumnSpans(gridItem.columns);
      }
      break;

    case "update":
      // 更新列宽时确保总宽度不超过24
      const totalSpan = gridItem.columns.reduce(
        (sum, col) => sum + col.span,
        0
      );
      if (totalSpan > 24) {
        redistributeGridColumnSpans(gridItem.columns);
      }
      break;
  }

  // 保存历史状态
  saveHistory();
};

// 重新分配栅格列宽
const redistributeGridColumnSpans = (columns) => {
  const totalColumns = columns.length;
  const spanPerColumn = Math.floor(24 / totalColumns);
  const remainder = 24 % totalColumns;

  columns.forEach((col, index) => {
    col.span = spanPerColumn + (index < remainder ? 1 : 0);
  });
};

// 预览表单
const previewForm = () => {
  previewModel.value = { ...formModel.value };
  previewVisible.value = true;
};

// 提交预览
const submitPreview = () => {
  console.log("预览表单数据:", previewModel.value);
  ElMessage.success("表单提交成功！");
};

// 清空表单
const clearForm = () => {
  formItems.value = [];
  formModel.value = {};
  selectedIndex.value = -1;

  // 保存历史状态
  saveHistory();
};

// 保存表单
const saveForm = async () => {
  const payload = {
    schemaId: props.schemaId ? props.schemaId : "",
    schemaJson: {
      formItems: JSON.parse(JSON.stringify(formItems.value)),
      formConfig: JSON.parse(JSON.stringify(formConfig)),
    },
  };
  try {
    let res;
    if (payload.schemaId) {
      res = await proxy.$API.codeManagement.formSchema.modify.post(payload);
    } else {
      res = await proxy.$API.codeManagement.formSchema.save.post(payload);
    }
    if (res && res.code === "01") {
      ElMessage.success("保存成功");
      router.push({ name: "SchemaList" });
    } else {
      ElMessage.error((res && res.msg) || "保存失败");
    }
  } catch (e) {
    ElMessage.error("保存失败");
  }
};

// 撤销操作
const undoAction = () => {
  if (canUndo.value) {
    historyIndex.value--;
    const state = historyStack.value[historyIndex.value];
    formItems.value = JSON.parse(JSON.stringify(state.formItems));
    formModel.value = JSON.parse(JSON.stringify(state.formModel));
    Object.assign(formConfig, state.formConfig);
    selectedIndex.value = -1;
  }
};

// 重做操作
const redoAction = () => {
  if (canRedo.value) {
    historyIndex.value++;
    const state = historyStack.value[historyIndex.value];
    formItems.value = JSON.parse(JSON.stringify(state.formItems));
    formModel.value = JSON.parse(JSON.stringify(state.formModel));
    Object.assign(formConfig, state.formConfig);
    selectedIndex.value = -1;
  }
};

// 初始化历史状态
const initHistory = () => {
  const initialState = {
    formItems: [],
    formModel: {},
    formConfig: { ...formConfig },
  };
  historyStack.value = [initialState];
  historyIndex.value = 0;
};

// 组件挂载时初始化历史
initHistory();

// 生成代码
const generateCode = () => {
  codeVisible.value = true;
};

// 导出表单配置
const exportForm = () => {
  try {
    const exportData = {
      formItems: formItems.value,
      formConfig: formConfig,
      formModel: formModel.value,
      version: "1.0.0",
      exportTime: new Date().toISOString(),
    };

    const dataStr = JSON.stringify(exportData, null, 2);
    const blob = new Blob([dataStr], { type: "application/json" });
    const url = URL.createObjectURL(blob);

    const link = document.createElement("a");
    link.href = url;
    link.download = `form-design-${Date.now()}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);

    ElMessage.success("表单配置导出成功！");
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("导出失败，请重试！");
  }
};

// 导入表单配置
const importForm = () => {
  const input = document.createElement("input");
  input.type = "file";
  input.accept = ".json";
  input.onchange = (event) => {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const importData = JSON.parse(e.target.result);

        // 验证导入数据的基本结构
        if (!importData.formItems || !Array.isArray(importData.formItems)) {
          throw new Error("无效的表单配置文件格式");
        }

        // 导入表单项
        formItems.value = importData.formItems || [];

        // 导入表单配置
        if (importData.formConfig) {
          Object.assign(formConfig, {
            labelWidth: "100px",
            labelPosition: "right",
            size: "default",
            showSubmitButton: true,
            showResetButton: false,
            events: {
              submit: "",
              reset: "",
              validate: "",
              validateField: "",
              clearValidate: "",
            },
            ...importData.formConfig,
          });
        }

        // 重建表单模型
        formModel.value = {};
        formItems.value.forEach((item) => {
          if (item.type !== "grid") {
            formModel.value[item.field] = getDefaultValue(item.type, item);
          } else if (item.columns) {
            // 处理栅格布局中的子组件
            item.columns.forEach((col) => {
              if (col.children) {
                col.children.forEach((child) => {
                  formModel.value[child.field] = getDefaultValue(
                    child.type,
                    child
                  );
                });
              }
            });
          }
        });

        // 重置选择状态
        selectedIndex.value = -1;
        selectedGridColumn.value = "";

        // 保存历史状态
        saveHistory();

        ElMessage.success("表单配置导入成功！");
      } catch (error) {
        console.error("导入失败:", error);
        ElMessage.error(`导入失败: ${error.message}`);
      }
    };
    reader.readAsText(file);
  };
  input.click();
};

const applySchema = (data) => {
  if (!data || !Array.isArray(data.formItems)) {
    return;
  }

  formItems.value = data.formItems || [];

  if (data.formConfig) {
    Object.assign(formConfig, {
      labelWidth: "100px",
      labelPosition: "right",
      size: "default",
      showSubmitButton: true,
      showResetButton: false,
      events: {
        submit: "",
        reset: "",
        validate: "",
        validateField: "",
        clearValidate: "",
      },
      ...data.formConfig,
    });
  }

  formModel.value = {};
  formItems.value.forEach((item) => {
    if (item.type !== "grid") {
      formModel.value[item.field] = getDefaultValue(item.type, item);
    } else if (item.columns) {
      item.columns.forEach((col) => {
        if (col.children) {
          col.children.forEach((child) => {
            formModel.value[child.field] = getDefaultValue(child.type, child);
          });
        }
      });
    }
  });

  selectedIndex.value = -1;
  selectedGridColumn.value = "";
  saveHistory();
};

watch(
  () => props.schema,
  (newVal) => {
    if (newVal) {
      applySchema(newVal);
    }
  },
  { immediate: true }
);
</script>

<style lang="less" scoped>
.form-designer {
  display: flex;
  height: 100%;
  background: var(--el-bg-color-page);
}
</style>
